<template>
  <div class="app-container">
    <!-- 顶部搜索区域 -->
    <div class="filter-container">
      <div class="search-container">
        <div class="search-item">
          <span class="search-title">教练名称</span>
          <el-input size="small" v-model="name" placeholder="请输入教练名称" style="width: 220px"></el-input>
        </div>
        <div class="search-item">
          <span class="search-title">专长领域</span>
          <el-input size="small" v-model="specialty" placeholder="请输入教练专长" style="width: 220px"></el-input>
        </div>
        <div class="search-item">
          <span class="search-title">认证信息</span>
          <el-input size="small" v-model="certification" placeholder="请输入教练认证信息" style="width: 220px"></el-input>
        </div>
        <div class="search-item">
            <span class="search-title">性别</span>
            <el-select v-model="gender" size="small" placeholder="请选择" style="width: 220px">
                <el-option
                v-for="item in genderOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                />
            </el-select>
        </div>
        <div class="search-item">
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </div>
      </div>
      <div class="right-container">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd">新增教练</el-button>
      </div>
    </div>

    <!-- 数据区域 -->
    <el-table :data="coachs" style="width: 100%;" height="700">
      <el-table-column prop="name" align="center" label="教练姓名"></el-table-column>
      <el-table-column prop="gender" align="center" label="性别">
        <template slot-scope="scope">
          <span>{{ scope.row.gender===1?'男':'女' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
      <el-table-column prop="specialty" label="专长领域" align="center"></el-table-column>
      <el-table-column prop="certification" label="教练认证" align="center"></el-table-column>
      <el-table-column prop="hireDate" label="入职日期" align="center"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" align="center"></el-table-column>
      <el-table-column label="操作" width="220" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">
            <i class="el-icon-edit" style="margin-right: -3px;"></i>
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="margin-right: 4px;"
            @click="handleDelete(scope.row)"
          >
            <i class="el-icon-delete" style="margin-right: -3px;"></i>
            删除
          </el-button>
          <el-dropdown size="mini">
            <el-button size="small" type="text">
              <i class="el-icon-d-arrow-right" style="margin-right: -5px;"></i>
              更多
            </el-button>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-form
        :model="formData"
        class="addDialog"
        :rules="rules"
        ref="formRef"
        size="small"
        label-width="120px"
      >
        <el-form-item label="教练姓名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>
        <el-form-item label="专长领域" prop="specialty">
          <el-input v-model="formData.specialty"></el-input>
        </el-form-item>
        <el-form-item label="教练认证" prop="certification">
          <el-input v-model="formData.certification"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="300px">
      <p align="center">确定要删除教练 {{ deleteCoachName }} 吗？</p>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script>
import { queryCoachs,getCoachById,addCoach,updateCoach } from "@/api/coach";
import { deleteFile } from "@/api/common";
export default {
  data() {
    return {
      uploadHeaders:{
        'X-Requested-With': 'XMLHttpRequest',
        'token': localStorage.getItem('token') || '',
      },
      uploadUrl: "/api/admin/common/upload",
      // 教练数据
      coachs: [],

      // 搜索筛选
      name: "",
      status: 1,
      specialty: "",
      certification: "",
      gender: null, // 新增字段，用于绑定下拉框选中的值
        genderOptions: [
            { label: '全部', value: null },
            { label: '男', value: 1 },
            { label: '女', value: 2 }
        ],

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 对话框
      dialogVisible: false,
      dialogType: "add", // 'add' 或 'edit'
      dialogTitle: "添加教练",
      formData: {
        name: "", // 教练姓名
        specialty: "",
        certification: "",
        gender: null, // 性别
        phone: "", // 手机号
        // hireDate: "" // 入职日期
      },

      // 表单验证规则
      rules: {
        name: [{ required: true, message: "请输入教练姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        specialty: [{ required: true, message: "请输入教练专长", trigger: "blur" }],
        certification: [{ required: true, message: "请输入教练认证", trigger: "change" }],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }]
      },

      // 删除相关
      deleteDialogVisible: false,
      deleteCoachId: "",
      deleteCoachName: ""
    };
  },


  methods: {
    // 分页
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.handleSearch();
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.handleSearch();
    },

    // 搜索
    handleSearch() {
        queryCoachs({
            page: this.currentPage,
            pageSize: this.pageSize,
            name: this.name,
            gender: this.gender,
            specialty: this.specialty,
            certification: this.certification,
            status: this.status
        }).then(res => {
            const data = res.data.data;
            this.coachs = data.records;
            this.total = data.total;
        })
    },

    // 添加员工
    handleAdd() {
      this.dialogType = "add";
      this.dialogTitle = "添加教练";
      // 重置表单数据
      this.formData = {
        name: "",
        specialty: "",
        certification: "",
        gender: null,
        phone: ""
      };
      this.dialogVisible = true;
    },

    // 编辑员工
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogTitle = "编辑教练";
      this.formData = { ...row }; // 复制对象，避免直接修改原数据
      this.dialogVisible = true;
    },

    // 保存员工信息
    handleSave() {
      // 调用表单的验证方法
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.dialogType === "add") {
            // 添加新教练
            console.log(this.formData)
            addCoach(this.formData).then((res)=>{
              if(res.data.code===1){
                this.$message.success("添加成功");
                this.dialogVisible = false;
                // 表格数据更新
                this.handleSearch();
              }else{
                this.$message.error(res.data.msg);
              }
            }).catch(error => {
              console.error('添加教练失败:', error);
              this.$message.error("添加教练失败，请重试");
            })

          } else {
            updateCoach(this.formData).then(res=>{
                if(res.data.code===1){
                this.$message.success("修改成功");
                this.dialogVisible = false;
                // 表格数据更新
                this.handleSearch();
              }else{
                this.$message.error(res.data.msg);
              }
            }).catch(error => {
              console.error('修改教练失败:', error);
              this.$message.error("修改教练失败，请重试");
            })
          }

        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },

    // 关闭对话框
    handleClose(done) {
      // 如果添加头像了，需要删除
      if (this.formData.avatar) {
        deleteFile(this.formData.avatar)
      }
      // 表单数据重置
      this.$refs.formRef.resetFields();
      done();
    },

    // 删除员工
    handleDelete(row) {
      this.deleteCoachId = row.id;
      this.deleteCoachName = row.name;
      this.deleteDialogVisible = true;
    },

    // 确认删除
    handleConfirmDelete() {
        // 构造参数：id + status（逻辑删除值）
        const params = {
            id: this.deleteCoachId,
            status: 0 // 0 表示已删除（根据你的业务定义）
        };
      updateCoach(params).then(res=>{
        if(res.data.code!==1){
          this.$message.error(res.data.msg)
        }else{
          this.$message.success("删除成功")
        }
        // 表格数据更新
        this.handleSearch();
      })
      this.deleteDialogVisible = false;
    }
  },
  mounted() {
    //初始化表格数据
    this.handleSearch();
  }
};
</script>
  
<style lang="less" scoped>
.app-container {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .filter-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    margin-bottom: 10px;

    .search-container {
      display: flex;

      .search-item {
        margin-right: 10px;

        .search-title {
          line-height: 32px;
          padding: 0 12px 0 0;
          color: #606266;
          font-size: 14px;
          font-weight: 700;
        }
      }
    }
  }

  .addDialog /deep/ .el-input {
    width: 280px;
  }

  .addDialog {
    .avatar-uploader::v-deep .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader::v-deep .el-upload:hover {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 80px;
      height: 80px;
      line-height: 80px;
      text-align: center;
    }

    .avatar {
      width: 80px;
      height: 80px;
      display: block;
    }
  }
}
</style>